﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace Tools
{
    public class Clone
    {
        public static T CloneObject<T>(T obj) where T : class
        {
            Type type = typeof(T);

            // 创建新对象
            T clone = Activator.CreateInstance(type) as T;

            // 获取所有字段
            FieldInfo[] fields = type.GetFields(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public);

            // 复制字段的值
            foreach (FieldInfo field in fields)
            {
                field.SetValue(clone, field.GetValue(obj));
            }

            // 获取所有属性
            PropertyInfo[] properties = type.GetProperties(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public);

            // 复制属性的值
            foreach (PropertyInfo property in properties)
            {
                if (property.CanWrite)
                {
                    property.SetValue(clone, property.GetValue(obj));
                }
            }

            return clone;
        }
    }
}

